package com.wu.store.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wu.store.annotation.CurrentUser;
import com.wu.store.common.util.MessageEntity;
import com.wu.store.common.util.PageUtils;
import com.wu.store.entity.Order;
import com.wu.store.entity.OrderInfo;
import com.wu.store.entity.OrderParams;
import com.wu.store.entity.User;
import com.wu.store.service.CartService;
import com.wu.store.service.OrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/order")
public class OrderController {
	@Autowired
	private OrderService orderService;
	@Autowired
	private CartService cartService;

	@RequestMapping("/list")
	public MessageEntity list(@CurrentUser User user, OrderParams orderParams) throws Exception {
		PageHelper.startPage(orderParams.getPage(), orderParams.getSize());
		List<Order> list = orderService.list(user.getId());
		PageInfo<Order> orderPageInfo = new PageInfo<>(list, 1);
		return new MessageEntity.Builder().success(true).data(PageUtils.getPageResult(orderPageInfo)).message("获取成功").create();
	}

	@RequestMapping("/info")
	public MessageEntity info(@CurrentUser User user, Long id) throws Exception {
		if (id == null) {
			throw new Exception("id必需");
		}
		OrderInfo info = orderService.info(user.getId(), id);
		return new MessageEntity.Builder().success(true).data(info).message("获取成功").create();
	}

	@RequestMapping("/add")
	public MessageEntity add(@CurrentUser User user, String ids) throws Exception {
		String[] split = StringUtils.split(ids, ",");
		if (split.length == 0) {
			throw new Exception("ids必需");
		}
		List<Long> idList = new ArrayList<>();
		for (String id : split) {
			idList.add(Long.parseLong(id));
		}
		Long orderId = orderService.add(user.getId(), idList);
		return new MessageEntity.Builder().success(true).message("创建订单成功").data(orderId).create();
	}

	@RequestMapping("/pay")
	public MessageEntity pay(@CurrentUser User user, Long id) throws Exception {
		Order order = new Order();
		order.setUid(user.getId());
		order.setId(id);
		order.setStatus(1);
		order.setPayTime(new Date());
		return new MessageEntity.Builder().success(orderService.update(order)).message("操作成功").create();
	}

	@RequestMapping("/delete")
	public MessageEntity delete(@CurrentUser User user, Long id) throws Exception {
		Order order = new Order();
		order.setUid(user.getId());
		order.setId(id);
		order.setStatus(-1);
		return new MessageEntity.Builder().success(orderService.update(order)).message("操作成功").create();
	}
}
